<?php

class Staff_collectionController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='create';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter'),
			array('application.filters.AuthFilter'),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow()
	{
		$this->render('show',array('model'=>$this->loadStaff_collection()));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{
		$model=new Staff_collection;
		if(isset($_POST['Staff_collection']))
		{
			$model->attributes=$_POST['Staff_collection'];
			if($model->save()){
				$this->redirect(array('show','id'=>$model->id,'ret'=>'create','ok'=>'0'));
			}	
		}
		$this->render('create',array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadStaff_collection();
		if(isset($_POST['Staff_collection']))
		{
			$model->attributes=$_POST['Staff_collection'];
			if($model->save()){
				$this->redirect(array('show','id'=>$model->id,'ret'=>'admin','ok'=>'1')+$_GET);  
			}
		}
		$this->render('update',array('model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			Staff_collection::model()->updateByPk($_GET['id'],array('state'=>1));
			unset($_GET['id']);
			$this->redirect(array('admin','ok'=>3)+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{	
		$this->search(false);
	}
	
	public function actionSearch(){
		$this->search();
	}
	
	private function search($method=true){
		$criteria=new CDbCriteria();
		$criteria->addCondition('staff_collection.state=0');
		$criteria->join='INNER JOIN drivers ON staff_collection.fk_driver_id=drivers.id';
		$criteria->select="staff_collection.id,drivers.name,date_format(staff_collection.examine_date,'%Y-%m') as examine_date,
		CONCAT(format(staff_collection.present_rate*100,0),'%') as present_rate,
		CONCAT(format(staff_collection.receipt_rate*100,0),'%') as receipt_rate,
		CONCAT(format(staff_collection.profit_rate*100,0),'%') as profit_rate,staff_collection.incentive_amount,
		CONCAT(format(staff_collection.aog_rate*100,0),'%') as aog_rate,
		CONCAT(format(staff_collection.exception_rate*100,0),'%') as exception_rate,
		CONCAT(format(staff_collection.attendance_rate*100,0),'%') as attendance_rate,staff_collection.amerce";
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key=='s_date'){//时间查询
					$criteria->addCondition("examine_date='{$val}-01'");
				}
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		if(isset($_GET['excel']))
			$this->toExcel($criteria);
		else	
			$this->toAdminPage($criteria,$method);
	}

	public function toAdminPage($criteria,$method){
		$model=Staff_collection::model();
		$pages=new CPagination($model->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['staff_collection'];
		$pages->applyLimit($criteria);
		
		$sort=new CSort('Staff_collection');
		$sort->defaultOrder='examine_date desc';
		$sort->attributes=array_merge($model->attributeNames(),array('name'));
		$sort->applyOrder($criteria);
    	$models=$model->findAll($criteria);
		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'search'=>$method,
		));
	}
	
	public function toExcel($criteria){
		$model=Staff_collection::model();
		$sort=new CSort('Staff_collection');
		$sort->defaultOrder='examine_date desc';
		$sort->attributes=array_merge($model->attributeNames(),array('name'));
		$sort->applyOrder($criteria);
    	$models=$model->findAll($criteria);

		$atrr_names=$model->attributeLabels();
		$excel_names=$model->excelAttributes();$end_cell=end($excel_names);
		$tab_name='员工月工作评比 ';
		$tab_name.=(isset($_GET['keys']['s_date'])?$_GET['keys']['s_date']:'');
		$tab_name=trim($tab_name);	
		
		require_once './protected/extensions/excel/PHPExcel.php';
		require_once './protected/extensions/excel/PHPExcel/IOFactory.php';
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)->setTitle($tab_name);
		$objPHPExcel->getActiveSheet()->mergeCells('A1:'.$end_cell[0].'1');
		$objPHPExcel->getActiveSheet()->setCellValue('A1',$tab_name);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(15);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal('center');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->setCellValue('A2','序号');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->freezePane('A3');//标题栏 冻结窗口
		foreach($excel_names as $attr=>$val){//创建标题
			$objPHPExcel->getActiveSheet()->setCellValue($val[0].'2',$atrr_names[$attr]);
			$objPHPExcel->getActiveSheet()->getColumnDimension($val[0])->setWidth($val[1]);
		}
		$row_index=3;//行索引 数据从3开始 例如A从A3开始添加数据
		foreach($models as $n=>$model){
			$objPHPExcel->getActiveSheet()->setCellValue('A'.($n+$row_index),$n+1);
			foreach($excel_names as $attr=>$val){//双循环，根据model内设置进行数据导出
				$value=$model->$attr;
				if(isset($val[2]))//值->字符串 转换
					$value=$model->$val[2]();
				$objPHPExcel->getActiveSheet()->setCellValue($val[0].($n+$row_index),$value);
			}
		}
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.iconv("utf-8", "gb2312", $tab_name.'.xls'));
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadStaff_collection($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$criteria=new CDbCriteria();
				$criteria->join='INNER JOIN drivers ON staff_collection.fk_driver_id=drivers.id';
				$criteria->select='drivers.name,staff_collection.*';
				$criteria->addCondition('staff_collection.id='.($id!==null ? $id : $_GET['id']));
				$this->_model=Staff_collection::model()->find($criteria);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	
	public function actionCheckStaffCollection(){
		if(Yii::app()->request->isAjaxRequest){
			if(isset($_POST['fk_driver_id'])&&isset($_POST['examine_date'])){
				$b=Staff_collection::model()->exists(array('condition'=>'fk_driver_id=:fk_driver_id and examine_date=:examine_date and state=0',
											'params'=>array(':fk_driver_id'=>$_POST['fk_driver_id'],':examine_date'=>$_POST['examine_date'].'-01')));
				echo $b?0:1;return;
			}			
		}
		echo 0;
	}
}
